package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.YddLinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/ydd_link")
public class YddLinkController {
    @Autowired
    private YddLinkService yddLinkService;
    @GetMapping("/list")
    public ResultData list(String type,String page,String limit){
        int pageI = Integer.parseInt(page);
        int pageSize = Integer.parseInt(limit);
        Page<YddLink> pageInfo = new Page<>(pageI, pageSize);
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddLink::getType,type);
        Page<YddLink> yddLinkPage = yddLinkService.page(pageInfo, queryWrapper);
        int count = yddLinkService.count(queryWrapper);

        List<YddLink> records = yddLinkPage.getRecords();
//        PageResult pageResult = new PageResult();
//        pageResult.setCounts(count);
//        pageResult.setPageSize((long) pageSize);
//        pageResult.setCurrentPage((long) pageI);
//        pageResult.setData(records);
//        pageResult.setTotalPage(pageTotal);
//        pageResult.init(count,size,current,records);
        PageResult pageResult = PageResult.init((long) count, (long) pageSize, (long) pageI, records);
        return ResultData.ok("",pageResult);

    }
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id){
        int idNum = Integer.parseInt(id);
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddLink::getId,idNum);
//        YddLink yddLink = yddLinkService.getById(queryWrapper);
        YddLink yddLink = yddLinkService.getById(id);
        return ResultData.ok("",yddLink);


    }
    @PostMapping("/update")
    public ResultData update(@RequestBody YddLink yddLink){
        if (yddLink==null){
            throw new BusinessException("信息不能为空");
        }
        yddLinkService.updateById(yddLink);
        return ResultData.ok("","修改成功");

    }
    @PostMapping("/add")
    public ResultData add(@RequestBody YddLink yddLink){
        if (yddLink==null){
            throw new BusinessException("信息不能为空");
        }
        yddLinkService.save(yddLink);
        return ResultData.ok("","添加成功");
    }
    @GetMapping("/del")
    public ResultData delete(String id){
        yddLinkService.removeById(id);
        return ResultData.ok("","删除成功");
    }
}
